package com.woniu108.car.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu108.car.client.PersonClient;
import com.woniu108.car.mapper.CarBrandMapper;
import com.woniu108.car.mapper.CarHotMapper;
import com.woniu108.car.mapper.CarSeriesMapper;
import com.woniu108.car.mapper.CarStyleMapper;
import com.woniu108.car.model.CarBrand;
import com.woniu108.car.model.CarHot;
import com.woniu108.car.model.CarSeries;
import com.woniu108.car.model.CarStyle;
import com.woniu108.car.param.*;
import com.woniu108.car.service.CarBrandService;
import com.woniu108.carService.commos.dto.AdminInfoDto;
import com.woniu108.carService.commos.exception.admin.AdminException;
import com.woniu108.carService.commos.exception.admin.AdminExceptionCode;
import com.woniu108.carService.commos.exception.car.CarException;
import com.woniu108.carService.commos.exception.car.CarExceptionCode;
import com.woniu108.carService.commos.exception.upload.UpLoadException;
import com.woniu108.carService.commos.exception.upload.UpLoadExceptionCode;
import com.woniu108.carService.commos.util.FileUtil;
import com.woniu108.carService.commos.util.OSSUtil;
import com.woniu108.carService.commos.util.StaticData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 车辆品牌表 服务实现类
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@Service
public class CarBrandServiceImpl extends ServiceImpl<CarBrandMapper, CarBrand> implements CarBrandService {

    @Resource
    private OSSUtil ossUtil;
    @Resource
    private PersonClient personClient;
    @Resource
    private CarBrandMapper carBrandMapper;
    @Resource
    private CarHotMapper carHotMapper;
    @Resource
    private CarSeriesMapper carSeriesMapper;
    @Resource
    private CarStyleMapper carStyleMapper;


    /**
     * @param image 图片文件
     * @return string
     * @throws Exception 自定义异常
     */
    private String handleImageUpload(MultipartFile image) throws Exception {
        // 判断文件类型
        if (!FileUtil.isImageFile(image.getInputStream())) {
            throw new UpLoadException(UpLoadExceptionCode.FILE_UPLOAD_ERROR);
        }

        String oldName = image.getOriginalFilename();
        if (oldName == null) {
            throw new UpLoadException(UpLoadExceptionCode.FILE_UPLOAD_NULL);
        }

        int lastIndex = oldName.lastIndexOf(".");
        if (lastIndex == -1) {
            throw new UpLoadException(UpLoadExceptionCode.FILE_UPLOAD_LACK_SUFFIX);
        }
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString();

        return ossUtil.uploadFile(image.getInputStream(), fileName + suffix, "class108");
    }

    /**
     * 判断管理员
     */
    private void isAdmin(String adminId) {
        // 检查 adminId 是否为 null
        if (adminId == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_ID_NULL);
        }
        // 判断管理员权限
        AdminInfoDto adminInfo = personClient.getByAdminId(adminId).getData();
        if (adminInfo == null) {
            throw new AdminException(AdminExceptionCode.ADMIN_NOT_HAVE);
        }
        if (adminInfo.getAdminRoleId() != 1) {
            throw new AdminException(AdminExceptionCode.ADMIN_NOT_PERMISSION);
        }
    }

    @Override
    public List<CarBrand> findAllCarBrand() {
        QueryWrapper<CarBrand> wrapper = new QueryWrapper<>();
        wrapper.ne("brand_state", StaticData.CAR_BRAND_STATE_DELETE);
        return carBrandMapper.selectList(wrapper);
    }

    @Override
    public List<CarBrand> findAllNormalCarBrand() {
        QueryWrapper<CarBrand> wrapper = new QueryWrapper<>();
        wrapper.eq("brand_state", StaticData.CAR_BRAND_STATE_NORMAL);
        return carBrandMapper.selectList(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertCarBrand(InsertCarBrandParam param) throws Exception {
        //判断管理员权限
        isAdmin(param.getAdminId());
        //图片转string
        String brandImage = handleImageUpload(param.getBrandImage());

        QueryWrapper<CarBrand> wrapper = new QueryWrapper<>();
        wrapper.eq("brand_name", param.getBrandName());
        CarBrand selectOne = carBrandMapper.selectOne(wrapper);
        if (selectOne != null) {
            if (selectOne.getBrandState().equals(StaticData.CAR_BRAND_STATE_BAN) || selectOne.getBrandState().equals(StaticData.CAR_BRAND_STATE_NORMAL)) {
                throw new CarException(CarExceptionCode.CAR_BRAND_HAVE);
            }
            selectOne.setBrandImage(brandImage);
            selectOne.setBrandState(StaticData.CAR_BRAND_STATE_NORMAL);
            carBrandMapper.updateById(selectOne);
        } else {
            CarBrand carBrand = new CarBrand();
            carBrand.setBrandName(param.getBrandName());
            carBrand.setBrandImage(brandImage);
            carBrand.setBrandState(StaticData.CAR_BRAND_STATE_NORMAL);
            carBrandMapper.insert(carBrand);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteCarBrand(DeleteCarBrandParam param) {
        //判断管理员权限
        isAdmin(param.getAdminId());
        for (Integer brandId : param.getBrandIds()) {
            //删除汽车品牌
            CarBrand carBrand = new CarBrand();
            carBrand.setBrandId(brandId);
            carBrand.setBrandState(StaticData.CAR_BRAND_STATE_DELETE);
            int brandUpdate = carBrandMapper.updateById(carBrand);
            if (brandUpdate <= 0) {
                throw new CarException(CarExceptionCode.CAR_BRAND_NOT_HAVE);
            }
            //删除汽车系列
            UpdateWrapper<CarSeries> seriesUpdateWrapper = new UpdateWrapper<>();
            seriesUpdateWrapper.set("series_state", StaticData.CAR_SERIES_STATE_DELETE);
            seriesUpdateWrapper.eq("brand_id", brandId);
            int seriesUpdate = carSeriesMapper.update(null, seriesUpdateWrapper);

            //删除款式
            UpdateWrapper<CarStyle> styleUpdateWrapper = new UpdateWrapper<>();
            styleUpdateWrapper.set("style_state", StaticData.CAR_STYLE_STATE_DELETE);
            styleUpdateWrapper.eq("brand_id", brandId);
            int styleUpdate = carStyleMapper.update(null, styleUpdateWrapper);

            //删除汽车热度榜
            UpdateWrapper<CarHot> hotUpdateWrapper = new UpdateWrapper<>();
            hotUpdateWrapper.set("hot_state", StaticData.CAR_HOT_STATE_DELETE);
            hotUpdateWrapper.eq("brand_id", brandId);
            carHotMapper.update(null, hotUpdateWrapper);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean banCarBrand(BanCarBrandParam param) {
        //判断管理员权限
        isAdmin(param.getAdminId());
        for (Integer brandId : param.getBrandIds()) {
            //禁用汽车品牌
            CarBrand carBrand = new CarBrand();
            carBrand.setBrandId(brandId);
            carBrand.setBrandState(StaticData.CAR_BRAND_STATE_BAN);
            CarBrand carBrand1 = carBrandMapper.selectById(brandId);
            if (Objects.equals(carBrand1.getBrandState(), StaticData.CAR_BRAND_STATE_DELETE)) {
                throw new CarException(CarExceptionCode.CAR_BRAND_STATE_DELETE);
            }
            if (Objects.equals(carBrand1.getBrandState(), StaticData.CAR_BRAND_STATE_BAN)) {
                throw new CarException(CarExceptionCode.CAR_BRAND_STATE_BAN);
            }
            int brandUpdate = carBrandMapper.updateById(carBrand);
            if (brandUpdate <= 0) {
                throw new CarException(CarExceptionCode.CAR_BRAND_NOT_HAVE);
            }
            //禁用汽车系列
            UpdateWrapper<CarSeries> seriesUpdateWrapper = new UpdateWrapper<>();
            seriesUpdateWrapper.set("series_state", StaticData.CAR_SERIES_STATE_BAN);
            seriesUpdateWrapper.eq("brand_id", brandId)
                    .ne("series_state", StaticData.CAR_SERIES_STATE_DELETE);
            carSeriesMapper.update(null, seriesUpdateWrapper);

            //禁用款式
            UpdateWrapper<CarStyle> styleUpdateWrapper = new UpdateWrapper<>();
            styleUpdateWrapper.set("style_state", StaticData.CAR_STYLE_STATE_BAN);
            styleUpdateWrapper.eq("brand_id", brandId)
                    .ne("style_state", StaticData.CAR_STYLE_STATE_DELETE);
            carStyleMapper.update(null, styleUpdateWrapper);


            //禁用汽车热度榜
            UpdateWrapper<CarHot> hotUpdateWrapper = new UpdateWrapper<>();
            hotUpdateWrapper.set("hot_state", StaticData.CAR_HOT_STATE_BAN);
            hotUpdateWrapper.eq("brand_id", brandId)
                    .ne("hot_state", StaticData.CAR_HOT_STATE_DELETE);
            carHotMapper.update(null, hotUpdateWrapper);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean unlockCarBrand(UnlockCarBrandParam param) {
        //判断管理员权限
        isAdmin(param.getAdminId());
        for (Integer brandId : param.getBrandIds()) {
            //解锁汽车品牌
            CarBrand carBrand = new CarBrand();
            carBrand.setBrandId(brandId);
            carBrand.setBrandState(StaticData.CAR_BRAND_STATE_NORMAL);
            CarBrand carBrand1 = carBrandMapper.selectById(brandId);
            if (Objects.equals(carBrand1.getBrandState(), StaticData.CAR_BRAND_STATE_DELETE)) {
                throw new CarException(CarExceptionCode.CAR_BRAND_STATE_DELETE);
            }
            if (Objects.equals(carBrand1.getBrandState(), StaticData.CAR_BRAND_STATE_NORMAL)) {
                throw new CarException(CarExceptionCode.CAR_BRAND_STATE_NORMAL);
            }
            int brandUpdate = carBrandMapper.updateById(carBrand);
            if (brandUpdate <= 0) {
                throw new CarException(CarExceptionCode.CAR_BRAND_NOT_HAVE);
            }
            //解锁汽车系列
            UpdateWrapper<CarSeries> seriesUpdateWrapper = new UpdateWrapper<>();
            seriesUpdateWrapper.set("series_state", StaticData.CAR_SERIES_STATE_NORMAL);
            seriesUpdateWrapper.eq("brand_id", brandId)
                    .ne("series_state", StaticData.CAR_SERIES_STATE_DELETE);
            carSeriesMapper.update(null, seriesUpdateWrapper);

            //解锁款式
            UpdateWrapper<CarStyle> styleUpdateWrapper = new UpdateWrapper<>();
            styleUpdateWrapper.set("style_state", StaticData.CAR_STYLE_STATE_NORMAL);
            styleUpdateWrapper.eq("brand_id", brandId)
                    .ne("style_state", StaticData.CAR_STYLE_STATE_DELETE);
            carStyleMapper.update(null, styleUpdateWrapper);
            //解锁汽车热度榜
            UpdateWrapper<CarHot> hotUpdateWrapper = new UpdateWrapper<>();
            hotUpdateWrapper.set("hot_state", StaticData.CAR_HOT_STATE_NORMAL);
            hotUpdateWrapper.eq("brand_id", brandId)
                    .ne("hot_state", StaticData.CAR_HOT_STATE_DELETE);
            carHotMapper.update(null, hotUpdateWrapper);

        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateCarBrandImage(UpdateCarBrandImageParam param) throws Exception {
        //图片装string
        String brandImage = handleImageUpload(param.getBrandImage());
        //判断管理员权限
        isAdmin(param.getAdminId());
        CarBrand carBrand = carBrandMapper.selectById(param.getBrandId());
        if (Objects.equals(carBrand.getBrandState(), StaticData.CAR_BRAND_STATE_DELETE)) {
            throw new CarException(CarExceptionCode.CAR_BRAND_STATE_DELETE);
        }
        carBrand.setBrandImage(brandImage);
        int i = carBrandMapper.updateById(carBrand);
        return i>0;
    }
}
